<template>
  <div class="main">
    <div class="login-box">
      <div class="title">Login</div>
      <div class="username-box">
        <div class="username">用户名</div>
        <el-input class="username-input" placeholder="请输入用户名" v-model="login.username"></el-input>
      </div>
      <div class="password-box">
        <div class="password">密码</div>
        <el-input class="password-input" placeholder="请输入密码" type="password" v-model="login.password"></el-input>
      </div>
      <div class="btn-box">
        <el-button class="btn" type="success" @click="login_handler">登录</el-button>
      </div>
      <div class="action-box">
        <el-button type="text" @click="showResetDialog">忘记密码？</el-button>
        <el-button type="text" @click="showRegisterDialog">注册账号</el-button>
      </div>
    </div>

    <!-- 注册对话框 -->
    <el-dialog title="注册账号" :visible.sync="registerDialogVisible" width="30%" center>
      <el-form :model="registerForm" :rules="registerRules" ref="registerForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名">
            <template slot="prepend">
              <i class="el-icon-user"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码">
            <template slot="prepend">
              <i class="el-icon-lock"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码">
            <template slot="prepend">
              <i class="el-icon-lock"></i>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="registerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRegister">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog :title="resetStep === 1 ? '验证身份' : '重置密码'" :visible.sync="resetDialogVisible" width="30%" center>
      <el-form :model="resetForm" :rules="resetRules" ref="resetForm" label-width="100px">
        <!-- 第一步：输入用户名 -->
        <el-form-item v-if="resetStep === 1" label="用户名" prop="username">
          <el-input v-model="resetForm.username" placeholder="请输入用户名">
            <template slot="prepend">
              <i class="el-icon-user"></i>
            </template>
          </el-input>
        </el-form-item>
        <!-- 第二步：输入验证码和新密码 -->
        <template v-if="resetStep === 2">
          <el-form-item label="验证码" prop="code">
            <el-input v-model="resetForm.code" placeholder="请输入验证码">
              <template slot="prepend">
                <i class="el-icon-key"></i>
              </template>
              <template slot="append">
                <el-button type="primary" @click="sendResetCode" :disabled="countdown > 0">
                  {{ countdown > 0 ? `${countdown}s后重试` : '发送验证码' }}
                </el-button>
              </template>
            </el-input>
            <!-- 邮箱做脱敏，保留前3位和后3位 -->
            <div v-if="email" class="email">验证码已发送到邮箱：{{ email.slice(0, 3) + '****' + email.slice(-3) }}</div>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="resetForm.newPassword" type="password" placeholder="请输入新密码">
              <template slot="prepend">
                <i class="el-icon-lock"></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="resetForm.confirmPassword" type="password" placeholder="请再次输入新密码">
              <template slot="prepend">
                <i class="el-icon-lock"></i>
              </template>
            </el-input>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleResetStep">{{ resetStep === 1 ? '下一步' : '确定' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { login, resetPasswordConfirm, add_user } from '@/api/user_api'
import { sendResetPassword } from '@/api/email'
import { AES_Encrypt } from '@/util/aes'

export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.resetForm.confirmPassword !== '') {
          this.$refs.resetForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.resetForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const validateRegisterPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.registerForm.confirmPassword !== '') {
          this.$refs.registerForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validateRegisterPass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      login: {
        username: "",
        password: ""
      },
      registerDialogVisible: false,
      resetDialogVisible: false,
      resetStep: 1,
      countdown: 0,
      countdownTimer: null,
      resetForm: {
        username: '',
        code: '',
        newPassword: '',
        confirmPassword: ''
      },
      resetRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      },
      email: '',
      registerForm: {
        username: '',
        password: '',
        confirmPassword: ''
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validateRegisterPass, trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validateRegisterPass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async login_handler() {
      if (!this.login.username) {
        this.$message({
          type: "error",
          message: "请输入用户名"
        })
        return
      }
      if (!this.login.password) {
        this.$message({
          type: "error",
          message: "请输入密码"
        })
        return
      }
      this.login.password = AES_Encrypt(this.login.password)
      const { data: res } = await login(this.login)
      this.$message({
        type: res.code == 200 ? 'success' : 'error',
        message: res.message
      })
      this.login.username = ""
      this.login.password = ""
      if (res.code == 200) {
        localStorage.setItem('user', JSON.stringify(res.data))
        localStorage.setItem('token', res.data.token)
        if (res.data.role_id == 1) {
          this.$router.push('/admin')
        } else {
          this.$router.push('/index/1')
        }
      }
    },
    showResetDialog() {
      this.resetDialogVisible = true
      this.resetStep = 1
      this.resetForm = {
        username: '',
        code: '',
        newPassword: '',
        confirmPassword: ''
      }
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer)
      }
    },
    async handleResetStep() {
      if (this.resetStep === 1) {
        // 验证用户名
        this.$refs.resetForm.validateField('username', async (error) => {
          if (!error) {
            this.resetStep = 2
          }
        })
      } else {
        // 重置密码
        this.$refs.resetForm.validate(async (valid) => {
          if (valid) {
            try {
              const res = await resetPasswordConfirm({
                username: this.resetForm.username,
                email: this.email,
                code: this.resetForm.code,
                newPassword: AES_Encrypt(this.resetForm.newPassword)
              })
              if (res.data.code === 200) {
                this.$message.success('密码重置成功')
                this.resetDialogVisible = false
              } else {
                this.$message.error(res.data.message)
              }
            } catch (error) {
              this.$message.error('密码重置失败')
            }
          }
        })
      }
    },
    async sendResetCode() {
      try {
        const res = await sendResetPassword(this.resetForm.username)
        if (res.data.code === 200) {
          this.$message.success('验证码已发送到您的邮箱')
          this.email = res.data.data.email
          this.countdown = 60
          this.countdownTimer = setInterval(() => {
            this.countdown--
            if (this.countdown <= 0) {
              clearInterval(this.countdownTimer)
            }
          }, 1000)
        } else {
          this.$message.error(res.data.message)
        }
      } catch (error) {
        this.$message.error('发送验证码失败')
      }
    },
    showRegisterDialog() {
      this.registerDialogVisible = true
      this.registerForm = {
        username: '',
        password: '',
        confirmPassword: ''
      }
    },
    async handleRegister() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          try {
            const res = await add_user({
              username: this.registerForm.username,
              password: AES_Encrypt(this.registerForm.password)
            })
            if (res.data.code === 200) {
              this.$message.success('注册成功')
              this.registerDialogVisible = false
            } else {
              this.$message.error(res.data.message)
            }
          } catch (error) {
            this.$message.error('注册失败')
          }
        }
      })
    }
  },
  beforeDestroy() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer)
    }
  }
}
</script>

<style scoped lang="scss">
.main {
  position: absolute;
  width: 100%;
  height: 100%;
  margin: 0;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: url("@/assets/bg.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  .login-box {
    border: 1px #dddadab4 solid;
    border-radius: 15px;
    width: 20%;
    height: 35%;
    margin-right: 10%;
    background-color: rgba(255, 255, 255, 0.7);
    backdrop-filter: blur(10px);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
    .title {
      font-size: 25px;
      font-weight: bold;
    }
    .username-box {
      width: 90%;
      display: flex;
      height: 20%;
      align-items: center;
      .username {
        width: 20%;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 5%;
      }
    }
    .password-box {
      display: flex;
      width: 90%;
      display: flex;
      .password {
        width: 20%;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 5%;
      }
    }
    .btn-box {
      width: 90%;
      display: flex;
      align-items: center;
      justify-content: center;
      .btn {
        width: 90%;
        font-size: 20px;
      }
    }
    .action-box {
      width: 90%;
      display: flex;
      justify-content: space-between;
      margin-top: -20px;
      .el-button {
        color: #409EFF;
        &:hover {
          color: #66b1ff;
        }
      }
    }
  }
}
</style>